package db

import (
	"fmt"
	"goProject/cfg"
	"log"
	"runtime"
	"time"

	"github.com/go-redis/redis"
)

var Redis *redis.Client

func init() {
	Redis = initLinkRedisDB(1)
}

func initLinkRedisDB(dbNum int) *redis.Client {
	timeout := 60 / runtime.GOMAXPROCS(0)
	if timeout < 3 {
		timeout = 3
	}
	client := redis.NewClient(&redis.Options{
		Addr:         fmt.Sprint(cfg.Password.Redis.IP, ":", cfg.Password.Redis.Port),
		Password:     cfg.Password.Redis.Password,
		DB:           dbNum,
		DialTimeout:  time.Duration(timeout+2) * time.Second,
		ReadTimeout:  time.Duration(timeout) * time.Second,
		WriteTimeout: time.Duration(timeout) * time.Second,
	})
	err := client.Ping().Err()
	if err != nil {
		fmt.Println("连接 Redis 数据库【", dbNum, "】失败：", err)
		time.Sleep(time.Second * 3)
		panic(err)
	}
	log.Println("连接 Redis 数据库【", dbNum, "】成功。")
	return client
}
